package utils

import (
	"regexp"
	"strings"
)

func TagUtilsParse(format string, tag string) map[string]string {
	origins := strings.Split(tag, "::")
	t := strings.Split(format, "::")

	ret := make(map[string]string)
	for i, key := range t {
		if !strings.HasPrefix(key, "{") || !strings.HasSuffix(key, "}") {
			continue
		}

		rp := regexp.MustCompile("\\{")
		rs := regexp.MustCompile("\\}")
		key = rp.ReplaceAllString(key, "")
		key = rs.ReplaceAllString(key, "")

		if i < len(origins) {
			ret[key] = origins[i]
		}
	}

	return ret
}

func TagUtilsIsMath(format string, tag string) bool {
	fmtFirstChar := format[0]
	if tag != "" && fmtFirstChar != tag[0] && fmtFirstChar != '{' {
		return false
	}

	if !strings.Contains(format, "::") {
		return format == tag
	}

	origins := strings.Split(tag, "::")
	t := strings.Split(format, "::")

	if len(origins) != len(t) {
		return false
	}

	var originKey string
	for i, fmtKey := range t {
		if strings.HasPrefix(fmtKey, "{") && strings.HasSuffix(fmtKey, "}") {
			continue
		}

		originKey = origins[i]
		if originKey != fmtKey {
			return false
		}
	}

	return true
}

func TagUtilsParseIfMath(format string, tag string) map[string]string {
	if !TagUtilsIsMath(format, tag) {
		return nil
	}

	return TagUtilsParse(format, tag)
}

func TagUtilsTagPatternToSqlPattern(tag string) string {
	r := regexp.MustCompile("\\{(.+?)\\}")
	return r.ReplaceAllString(tag, "%")
}
